import 'package:edu/pages/common/five_start_rating_widget.dart';
import 'package:flutter/material.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/pages/course/course_review/course_review_page_logic.dart';
import 'package:provider/provider.dart';

class CourseReviewPage extends StatefulWidget {
  const CourseReviewPage({super.key});

  @override
  State<CourseReviewPage> createState() => _CourseReviewPageState();
}

class _CourseReviewPageState extends State<CourseReviewPage> {
  @override
  void initState() {
    super.initState();

    context.read<CourseReviewPageLogic>().init();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _buildAppBar(context),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: Column(
          children: [
            const SizedBox(height: 25),
            _buildRatingWidget(context),
            const SizedBox(height: 30),
            _buildReplyEditorWidget(context),
          ],
        ),
      ),
    );
  }

  Widget _buildRatingWidget(BuildContext context) {
    final logic = context.read<CourseReviewPageLogic>();
    final rating = logic.rating;
    return Row(
      children: [
        Text(
          AppStrings.myRating,
          style: Theme.of(context).textTheme.titleLarge,
        ),
        const Spacer(),
        FiveStartRatingWidget(
          rating: rating,
          starSize: 24,
          onRatingChanged: (v) {
            logic.newRating = v;
          },
        ),
      ],
    );
  }

  Widget _buildReplyEditorWidget(BuildContext context) {
    final logic = context.read<CourseReviewPageLogic>();
    return TextField(
      decoration: const InputDecoration(
        labelText: AppStrings.myReview,
        labelStyle: TextStyle(fontSize: 22, height: 0.75),
        hintText: AppStrings.replyHint,
        contentPadding: EdgeInsets.only(top: 0),
      ),
      controller: logic.controller,
      focusNode: logic.focusNode,
      autofocus: true,
      maxLength: 500,
      maxLines: 8,
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    final fontSize = Theme.of(context).textTheme.titleMedium?.fontSize ?? 16;
    return AppBar(
      title: Text(AppStrings.editReview, style: TextStyle(fontSize: fontSize)),
      leadingWidth: 80,
      leading: TextButton(
        child: Text(AppStrings.cancel, style: TextStyle(fontSize: fontSize)),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: [
        TextButton(
          child: Text(AppStrings.confirm, style: TextStyle(fontSize: fontSize)),
          onPressed: () {
            final logic = context.read<CourseReviewPageLogic>();
            logic.review().then((value) {
              if (value != null) {
                Navigator.of(context).pop(value);
              }
            });
          },
        ),
      ],
    );
  }
}
